package com.esm.view;

import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.esm.app.MyApplication;
import com.esm.tool.BaseActivity;
import com.esm.tool.Utils;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

//饼图
public class Second2Activity extends BaseActivity {
    private final TextView[] text = new TextView[7];
    private final TextView[] text_2 = new TextView[12];
    private final TextView[] text_3 = new TextView[12];

    private final ArrayList<String> listZ = new ArrayList<String>();
    private final ArrayList<String> listZ2 = new ArrayList<String>();
    private final ArrayList<String> listZ3 = new ArrayList<String>();
    private final ArrayList<String> list = new ArrayList<String>();
    private final ArrayList<Integer> list1 = new ArrayList<Integer>();
    private final ArrayList<String> list_2 = new ArrayList<String>();
    private final ArrayList<Integer> list1_2 = new ArrayList<Integer>();
    private final ArrayList<String> list_3 = new ArrayList<String>();
    private final ArrayList<Integer> list1_3 = new ArrayList<Integer>();
    private final String url = MyApplication.SERVERPATH + "/Y502/TvgetTongji1";
    private final String url2 = MyApplication.SERVERPATH + "/Y502/TvgetTongji2";
    private final String url3 = MyApplication.SERVERPATH + "/Y502/TvgetTongji3";
    MyThread thread = null;
    SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd");
    String shijian = "";
    float sc = 0, zsc, pph, rft;
    int dqmb = 0;
    int jpcl = 0;
    int bad, jinshu, hege, mmbcl, dcl, pph2;
    String dclstr, dqclstr, pphstr, yichangstr;
    RequestQueue mQueue = null;
    JsonObjectRequest mJsonObjectRequest = null;
    String sstr = "javascript:createChart([],[]);";
    Calendar ca = Calendar.getInstance();
    DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
    boolean b = true;
    private WebView web1;
    private TextView ttime;
    private TextView ttitle;
    private TextView ttishi;
    LinearLayout l_02;
    LinearLayout l_03;

    Handler mHander = new Handler() {
        public void handleMessage(Message msg) {
            try {
                switch (msg.what) {
                    case 1:
                        ttishi.setText(yichangstr);
                        break;
                    case 2: {
                        JSONObject json = (JSONObject) msg.obj;
                        String re = json.getString("result");
                        String name = "";
                        if (re.equals("yes")) {

                            JSONArray array = json.optJSONArray("data");
                            if (array != null && array.length() > 0) {
                                String a = "[";
                                String b = "[";
                                if (urlmodel == 1) {
                                    list.clear();
                                    list1.clear();
                                    listZ.clear();
                                } else if (urlmodel == 2) {
                                    list_2.clear();
                                    list1_2.clear();
                                    listZ2.clear();
                                }  else if (urlmodel == 3) {
                                    list_3.clear();
                                    list1_3.clear();
                                    listZ3.clear();
                                }

                                for (int i = 0; i < array.length(); i++) {
                                    if (!a.equals("[")) {
                                        a += "',";
                                        b += ",";
                                    }
                                    JSONObject obj = array.optJSONObject(i);
                                    name = obj.getString("name");
                                    if (urlmodel == 1) {
                                        listZ.add(name);//中文
                                    } else if (urlmodel == 2) {
                                        listZ2.add(name);//中文
                                    }  else if (urlmodel == 3) {
                                        listZ3.add(name);//中文
                                    }

                                    String name2 = name;//越南语
                                    if (MyApplication.yy.equals("en"))
                                        name2 = obj.getString("nameen");
                                    else if (MyApplication.yy.equals("vi"))
                                        name2 = obj.getString("namevi");

                                    if (name2.isEmpty()) {
                                        name2 = Utils.getLeixing(context, MyApplication.yy, name);
                                    }

                                    int num = obj.getInt("num");

                                    if (urlmodel == 1) {
                                        list.add(name2);
                                        list1.add(num);
                                    } else if (urlmodel == 2) {
                                        list_2.add(name2);
                                        list1_2.add(num);
                                    }  else if (urlmodel == 3) {
                                        list_3.add(name2);
                                        list1_3.add(num);
                                    }
                                    a += "'" + name2;
                                    b += num;
                                }
                                a += "']";
                                b += "]";
                                sstr = "javascript:createChart(" + a + "," + b + ");";
                                web1.reload();

                                if (urlmodel == 1) {
                                    initList(list);
                                } else if (urlmodel == 2) {
                                    initList(list_2);
                                }  else if (urlmodel == 3) {
                                    initList(list_3);
                                }

                            } else {
                                if (urlmodel == 1) {
                                    list.clear();
                                    list1.clear();
                                } else if (urlmodel == 2) {
                                    list_2.clear();
                                    list1_2.clear();
                                }  else if (urlmodel == 3) {
                                    list_3.clear();
                                    list1_3.clear();
                                }

                                sstr = "javascript:createChart([],[]);";
                                web1.reload();
                                initList(list);
                            }
                        } else {
                            ttishi.setText(yichangstr);
                        }
                        break;
                    }
                }

            } catch (Exception e) {

            }
        }
    };
    private String jintian;
    private TextView shang;
    private TextView fan;
    private int urlmodel = 1;
    private String leixing = "", tt1, tt2;
    private long firstTime = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_second);

        String sta = MyApplication.yy;
        Locale myLocale = new Locale(sta);
        Resources res = getResources();
        DisplayMetrics dm = res.getDisplayMetrics();
        Configuration conf = res.getConfiguration();
        conf.locale = myLocale;
        res.updateConfiguration(conf, dm);

        long thistime = MyApplication.xtime * 1000 + System.currentTimeMillis();
        shijian = df1.format(new Date(thistime));//"2019-01-11";
        jintian = shijian;
        mQueue = MyApplication.getRequestQueue();
        setView();
        setSystemUIVisible(false);
        thread = new MyThread();
        thread.start();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.but1:
                //上一天
                urlmodel = 1;
                l_02.setVisibility(View.GONE);
                l_03.setVisibility(View.GONE);
                try {
                    Date date = format1.parse(shijian);
                    ca.setTime(date);
                    ca.add(Calendar.DATE, -1);
                    Date start = ca.getTime();
                    shijian = df1.format(start);
                    ttime.setText(shijian);
                    thread = new MyThread();
                    thread.start();
                    leixing = "";
                    ttitle.setText(text[4].getText().toString());
                    ttitle.setText(R.string.taitou);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                break;
            case R.id.but3:
                //返回首页
//                if (urlmodel == 2 || !ttime.getText().equals(jintian)) {
//                    long thistime = MyApplication.xtime * 1000 + System.currentTimeMillis();
//                    shijian = df1.format(new Date(thistime));
//                    jintian = shijian;
//                    ttime.setText(shijian);
//                    urlmodel = 1;
//                    leixing = "";
//                    thread = new MyThread();
//                    thread.start();
//                    shang.setEnabled(true);
//                    shang.setVisibility(View.VISIBLE);
//                    ttitle.setText(R.string.taitou);
//                } else if (urlmodel == 1)
//                    this.finish();
//                else {
//                    urlmodel = 2;
//                    leixing = tt1;
//                    thread = new MyThread();
//                    thread.start();
//                    String name = Utils.getLeixing(context, MyApplication.yy, tt1);
//                    ttitle.setText(name);
//                }
                this.finish();
                break;
            case R.id.but4:
                onL(0);
                break;
            case R.id.but5:
                onL(1);
                break;
            case R.id.but6:
                onL(2);
                break;
            case R.id.but7:
                onL(3);
                break;
            case R.id.but8:
                onL(4);
                break;
            case R.id.but9:
                onL(5);
                break;
            case R.id.but10:
                onL(6);
                break;
            case R.id.but1_2:
                onL2(0);
                break;
            case R.id.but2_2:
                onL2(1);
                break;
            case R.id.but3_2:
                onL2(2);
                break;
            case R.id.but4_2:
                onL2(3);
                break;
            case R.id.but5_2:
                onL2(4);
                break;
            case R.id.but6_2:
                onL2(5);
                break;
            case R.id.but7_2:
                onL2(6);
                break;
            case R.id.but8_2:
                onL2(7);
                break;
            case R.id.but9_2:
                onL2(8);
                break;
            case R.id.but10_2:
                onL2(9);
                break;
            case R.id.but11_2:
                onL2(10);
                break;
            case R.id.but12_2:
                onL2(11);
                break;
        }
    }

    private void onL(int i) {
        urlmodel = 2;
        leixing = listZ.get(i);
        thread = new MyThread();
        thread.start();
        tt1 = leixing;
        ttitle.setText(list.get(i));
        l_02.setVisibility(View.VISIBLE);
        l_03.setVisibility(View.GONE);

        for (int k = 0; k < 7; k++) {
            text[k].setTextColor(context.getResources().getColor(R.color.white));
        }
        for (int k = 0; k < 12; k++) {
            text_2[k].setTextColor(context.getResources().getColor(R.color.white));
        }
        text[i].setTextColor(context.getResources().getColor(R.color.show_normal));
    }

    private void onL2(int i) {
        urlmodel = 3;
        tt2 = listZ2.get(i);
        thread = new MyThread();
        thread.start();
        l_03.setVisibility(View.VISIBLE);

        for (int k = 0; k < 12; k++) {
            text_2[k].setTextColor(context.getResources().getColor(R.color.white));
        }
        text_2[i].setTextColor(context.getResources().getColor(R.color.show_normal));
    }

    private void initList(ArrayList list) {
        int num = list.size() - 1;
        if (urlmodel == 1) {
            for (int i = 0; i < 7; i++) {
                if (i <= num) {
                    text[i].setEnabled(true);
                    text[i].setVisibility(View.VISIBLE);
                    text[i].setText(list.get(i) + ": " + list1.get(i));
                } else {
                    text[i].setEnabled(false);
                    text[i].setVisibility(View.GONE);
                }
            }
        } else if (urlmodel == 2) {
            for (int i = 0; i < 12; i++) {
                if (i <= num) {
                    text_2[i].setEnabled(true);
                    text_2[i].setVisibility(View.VISIBLE);
                    text_2[i].setText(list_2.get(i) + ": " + list1_2.get(i));
                } else {
                    text_2[i].setEnabled(false);
                    text_2[i].setVisibility(View.GONE);
                }
            }
        }  else if (urlmodel == 3) {
            for (int i = 0; i < 12; i++) {
                if (i <= num) {
                    text_3[i].setEnabled(true);
                    text_3[i].setVisibility(View.VISIBLE);
                    text_3[i].setText(list_3.get(i) + ": " + list1_3.get(i));
                } else {
                    text_3[i].setEnabled(false);
                    text_3[i].setVisibility(View.GONE);
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        b = false;
        super.onDestroy();
    }

    private void getData() {
        boolean isConnected = Utils.toastIsNetworkConnected(this);
        if (isConnected) {
            //showProgressBar();
            String uu = url + "?riqi=" + shijian;
            try {
                if (urlmodel == 2) {
                    leixing = URLEncoder.encode(leixing, "UTF-8");
                    uu = url2 + "?riqi=" + shijian + "&&leixing=" + leixing;
                } else if (urlmodel == 3) {
                    String lt = URLEncoder.encode(tt2, "UTF-8");
                    uu = url3 + "?riqi=" + shijian + "&&name=" + lt;
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            mJsonObjectRequest = new JsonObjectRequest(Request.Method.POST, uu,
                    null, new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    hideProgressBar();
                    parseData(response);
                }


            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    showToast(getString(R.string.network_error_try_again));
                    Message msg = mHander.obtainMessage();
                    msg.what = 1;
                    mHander.sendMessage(msg);
                }
            }
            );
            mQueue.add(mJsonObjectRequest);
        } else {
            showToast(getString(R.string.network_error_try_again));
            Message msg = mHander.obtainMessage();
            msg.what = 1;
            mHander.sendMessage(msg);
            return;
        }
    }

    protected void parseData(JSONObject response) {
        Message msg = mHander.obtainMessage();
        msg.what = 2;
        msg.obj = response;
        mHander.sendMessage(msg);
    }

    private void setView() {
        web1 = (WebView) findViewById(R.id.second_web1);
        ttime = (TextView) findViewById(R.id.second_time);
        ttime.setText(shijian);
        ttitle = (TextView) findViewById(R.id.second_title);
        ttitle.setText(getString(R.string.taitou));
        text[0] = (TextView) findViewById(R.id.but4);
        text[0].setOnClickListener(this);
        text[1] = (TextView) findViewById(R.id.but5);
        text[1].setOnClickListener(this);
        text[2] = (TextView) findViewById(R.id.but6);
        text[2].setOnClickListener(this);
        text[3] = (TextView) findViewById(R.id.but7);
        text[3].setOnClickListener(this);
        text[4] = (TextView) findViewById(R.id.but8);
        text[4].setOnClickListener(this);
        text[5] = (TextView) findViewById(R.id.but9);
        text[5].setOnClickListener(this);
        text[6] = (TextView) findViewById(R.id.but10);
        text[6].setOnClickListener(this);
        shang = (TextView) findViewById(R.id.but1);
        shang.setOnClickListener(this);
        shang.setText(getString(R.string.shang));
        fan = (TextView) findViewById(R.id.but3);
        String strFan = getString(R.string.fan);
        fan.setText(strFan);
        fan.setOnClickListener(this);
        //ttitle.setText(taitou);
        ttishi = (TextView) findViewById(R.id.second_tishi);
        web1.getSettings().setAllowFileAccess(true);
        web1.getSettings().setJavaScriptEnabled(true);
        web1.loadUrl("file:///android_asset/echart/index2.html");
        web1.setWebViewClient(new WebViewClient() {
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                return super.shouldOverrideUrlLoading(view, url);
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {

                super.onPageStarted(view, url, favicon);
            }

            public void onPageFinished(WebView view, String url) {
                Log.e("123", sstr);
                web1.loadUrl(sstr);
            }
        });

        //---新增
        l_02 = (LinearLayout) findViewById(R.id.l_02);
        l_03 = (LinearLayout) findViewById(R.id.l_03);

        l_02.setVisibility(View.GONE);
        l_03.setVisibility(View.GONE);

        text_2[0] = (TextView) findViewById(R.id.but1_2);
        text_2[0].setOnClickListener(this);
        text_2[1] = (TextView) findViewById(R.id.but2_2);
        text_2[1].setOnClickListener(this);
        text_2[2] = (TextView) findViewById(R.id.but3_2);
        text_2[2].setOnClickListener(this);
        text_2[3] = (TextView) findViewById(R.id.but4_2);
        text_2[3].setOnClickListener(this);
        text_2[4] = (TextView) findViewById(R.id.but5_2);
        text_2[4].setOnClickListener(this);
        text_2[5] = (TextView) findViewById(R.id.but6_2);
        text_2[5].setOnClickListener(this);
        text_2[6] = (TextView) findViewById(R.id.but7_2);
        text_2[6].setOnClickListener(this);
        text_2[7] = (TextView) findViewById(R.id.but8_2);
        text_2[7].setOnClickListener(this);
        text_2[8] = (TextView) findViewById(R.id.but9_2);
        text_2[8].setOnClickListener(this);
        text_2[9] = (TextView) findViewById(R.id.but10_2);
        text_2[9].setOnClickListener(this);
        text_2[10] = (TextView) findViewById(R.id.but11_2);
        text_2[10].setOnClickListener(this);
        text_2[11] = (TextView) findViewById(R.id.but12_2);
        text_2[11].setOnClickListener(this);

        text_3[0] = (TextView) findViewById(R.id.but1_3);
        text_3[1] = (TextView) findViewById(R.id.but2_3);
        text_3[2] = (TextView) findViewById(R.id.but3_3);
        text_3[3] = (TextView) findViewById(R.id.but4_3);
        text_3[4] = (TextView) findViewById(R.id.but5_3);
        text_3[5] = (TextView) findViewById(R.id.but6_3);
        text_3[6] = (TextView) findViewById(R.id.but7_3);
        text_3[7] = (TextView) findViewById(R.id.but8_3);
        text_3[8] = (TextView) findViewById(R.id.but9_3);
        text_3[9] = (TextView) findViewById(R.id.but10_3);
        text_3[10] = (TextView) findViewById(R.id.but11_3);
        text_3[11] = (TextView) findViewById(R.id.but12_3);
    }


    private void setSystemUIVisible(boolean show) {
        if (show) {
            int uiFlags = View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            uiFlags |= 0x00001000;
            getWindow().getDecorView().setSystemUiVisibility(uiFlags);
        } else {
            int uiFlags = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_FULLSCREEN;
            uiFlags |= 0x00001000;
            getWindow().getDecorView().setSystemUiVisibility(uiFlags);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                long secondTime = System.currentTimeMillis();
                if (secondTime - firstTime > 2000) {
                    Toast.makeText(this, "再点击一次退出！", Toast.LENGTH_SHORT).show();
                    firstTime = secondTime;
                    return true;
                } else {
                    exit();
                }
                break;
        }
        return super.onKeyUp(keyCode, event);
    }

    class MyThread extends Thread {
        @Override
        public void run() {
            try {
                getData();
            } catch (Exception e) {
            }
        }
    }
}
